package game.leon.seawar.vo;

import java.io.*;

/**
 * User: bianpeng
 * Date: 11-12-29
 * 封装一下用到的读写数据类型
 * 需要注意, 就是空字符串的处理, 有一个short来指示字符串长度
 */
public class ByteBuffer {
    // 输出用
    private ByteArrayOutputStream outputStream;
    private DataOutputStream dataOutputStream;
    // 输入用
    private ByteArrayInputStream inputStream;
    private DataInputStream dataInputStream;
    // use for output
    public ByteBuffer() {
        outputStream = new ByteArrayOutputStream();
        dataOutputStream = new DataOutputStream(outputStream);
    }
    // use for input
    public ByteBuffer(byte[] data) {
        inputStream = new ByteArrayInputStream(data);
        dataInputStream = new DataInputStream(inputStream);
    }
    public void write_short(int val) throws IOException {
        dataOutputStream.writeShort(val);
    }
    public void write_int(int val) throws IOException {
        dataOutputStream.writeInt(val);
    }
    public void write_double(double val) throws IOException {
        dataOutputStream.writeDouble(val);
    }
    public void write_string(String val) throws IOException {
        if (val == null || val.length() == 0) {
            dataOutputStream.writeShort(0);
        } else {
            dataOutputStream.writeUTF(val);
        }
    }
    //////////////////////////////////////////////////////////////////////////////
    public short read_short() throws IOException {
        return dataInputStream.readShort();
    }
    public int read_int() throws IOException {
        return dataInputStream.readInt();
    }
    public double read_double() throws IOException {
        return dataInputStream.readDouble();
    }
    public String read_string() throws IOException {
        return dataInputStream.readUTF();
    }
    public int remain_length() throws IOException {
        return inputStream.available();
    }
    public byte[] to_bytes() {
        return outputStream.toByteArray();
    }
}
